package com.xinqi.common.mybatis.type;

import com.xinqi.common.base.utils.json.JSON;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * JsonNode转换
 */
public class JsonObjectTypeHandler<T> extends BaseTypeHandler<T> {

    private Class<T> type;

    private final BaseTypeHandler targetTypeHandler;

    public JsonObjectTypeHandler(Class<T> type, BaseTypeHandler targetTypeHandler) {
        if (type == null) {
            throw new IllegalArgumentException("Type argument cannot be null");
        }
        this.type = type;
        this.targetTypeHandler = targetTypeHandler;
    }

    @Override
    @SuppressWarnings("unchecked")
    public void setNonNullParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException {
        if (targetTypeHandler != null) {
            targetTypeHandler.setNonNullParameter(ps, i, parameter, jdbcType);
            return;
        }
        ps.setString(i, JSON.stringify(parameter));
    }

    @Override
    public T getNullableResult(ResultSet rs, String columnName) throws SQLException {
        if (targetTypeHandler != null) {
            return (T) targetTypeHandler.getNullableResult(rs, columnName);
        }
        String result = rs.getString(columnName);
        return toJsonNode(result);
    }

    @Override
    @SuppressWarnings("unchecked")
    public T getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        if (targetTypeHandler != null) {
            return (T) targetTypeHandler.getNullableResult(rs, columnIndex);
        }
        String result = rs.getString(columnIndex);
        return toJsonNode(result);
    }

    @Override
    @SuppressWarnings("unchecked")
    public T getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        if (targetTypeHandler != null) {
            return (T) targetTypeHandler.getNullableResult(cs, columnIndex);
        }
        String result = cs.getString(columnIndex);
        return toJsonNode(result);
    }

    private T toJsonNode(String s) {
        if (s == null) {
            return null;
        }
        try {
            return JSON.parse(s, type);
        } catch (Exception e) {
            throw new IllegalArgumentException("Cannot convert [ " + s + " ] to JsonNode.", e);
        }
    }

}
